package com.jsz.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.jsz.constant.MessageConstant;
import com.jsz.constant.RedisMessageConstant;
import com.jsz.entity.Result;
import com.jsz.pojo.Member;
import com.jsz.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/*
    用户手机快速登录
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/telephoneLogin")
    public Result telephoneLogin(HttpServletResponse response, @RequestBody Map map) {
        //获取用户填写的手机号
        String telephone = (String) map.get("telephone");
        //获取用户输入的验证码
        String validateCode = (String) map.get("validateCode");
        //从redis缓存中获取保存的用户登录验证码
        String telephoneCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        System.out.println(telephone);
        System.out.println(validateCode);
        System.out.println(telephoneCodeInRedis);

        if (telephoneCodeInRedis != null && telephone != null && validateCode != null && validateCode.equals(telephoneCodeInRedis)) {
            //验证码正确,查询会员信息
            Member member = memberService.findByTelephone(telephone);
            //判断用户是否是会员
            if (member == null) {
                //不是会员,帮用户自动注册会员
                member = new Member();
                member.setPhoneNumber(telephone);//设置用户手机号
                member.setRegTime(new Date());//设置会员注册时间
                //调用业务层,将重新复制的会员信息,添加到用户会员表中
                memberService.add(member);
            }
            //是会员,将用户的信息保存到cookie中
            Cookie cookie = new Cookie("Login_Member_Telephone", telephone);
            //设置cookie的作用域范围.这里的/表示访问网站时,前面的www.baidu.com/.配置/之后就能完成自动回显手机号到页面中
            cookie.setPath("/");
            //设置cookie的存放数据时间
            cookie.setMaxAge(60 * 60 * 24 * 30);//cookie存放数据时间为30天
            //回写cookie数据给浏览器
            response.addCookie(cookie);
            //因为redis中不能保存member这样的java对象,所以需要将对象转换成json格式在保存到redis中
            String json = JSON.toJSON(member).toString();
            //将会员信息保存到redis服务器中
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);

        } else {
            //验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
